package com.microcity.newframe.rx;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.microcity.newframe.mvp.model.entity.BaseEntity;
import com.microcity.newframe.widget.dialog.Loading;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import rx.Observer;


/**
 * Created by Darksiderl on 5/3/16.
 */
public class RxObserver<T> implements Observer<T> {
    private final Context mContext;
    private final RxResult<T> mResult;

    public RxObserver(Context context, RxResult<T> result) {
        this.mContext = context;
        this.mResult = result;
    }

    @Override
    public void onCompleted() {

    }

    @Override
    public void onError(Throwable e) {
        Loading.dismiss();
        if (null != mContext) {
            if (e instanceof ConnectException) {
                Toast.makeText(mContext, "网络连接失败，请重试", Toast.LENGTH_SHORT).show();
            } else if (e instanceof SocketTimeoutException) {
                Toast.makeText(mContext, "网络连接超时", Toast.LENGTH_SHORT).show();
            }
            if (e.getMessage() != null) {
                Log.e("RequestApi", "onError --->" + e.getClass() + "&&message --->" + e.getMessage());
            }
        }
    }


    @Override
    public void onNext(T t) {
        if (t instanceof BaseEntity) {
//      if (((Result) t).getResult() == 0) {
            mResult.onResult(t);
//      }
        }
    }

    public interface RxResult<T> {
        void onResult(T t);
    }
}
